package cn.tradewin.pmp.pages.security;

import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Log;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.slf4j.Logger;

import cn.tradewin.pmp.persist.model.Contract;

public class AddContractMain extends AddContract {

	@Property
	private Contract contract;

	@InjectPage
	private AddContractDetail detail;

	@Component(id = "form")
	private Form form;
	
	@Inject
	Logger log;

	@Override
	public void startConversation() {
		super.startConversation();
		contract = new Contract();
		this.saveContractToConversation(contract);
	}

	@Log
	@OnEvent(value=EventConstants.PREPARE)
	void onPrepare() {
		if (contract == null) {
			contract = this.restoreContractFromConversation();
		}
	}

	void onValidateFromForm() {
		if (form.getHasErrors()) {
			// We get here only if a server-side validator detected an error.
			return;
		}
		this.saveContractToConversation(contract);
	}

	@Log
	Object onSuccess() {
		detail.set(this.getConversationId());
		return detail;
	}

	Object onQuit() {
		this.endConversation();
		return null;
	}
}
